package mobi.weq.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Set;
import java.util.TreeSet;

public class Database {

	private static String url = "jdbc:mysql://localhost:3306/";
	private static String driverName = "com.mysql.jdbc.Driver";
	private static String userName = "root";
	private static String password = "moazzam";
	private static String dbName = "weqmobi";
	private static Set<String> tables = new TreeSet<String>() {
		{
			add("user");
			add("so_template");
			add("uo_template");
		}
	};

	private static Connection dbCon = null;

	/**
	 * get connection to do database operations
	 * 
	 * @return
	 * @throws SQLException
	 */
	public static Connection getConnection() {
		try {
			if (dbCon == null || dbCon.isClosed()) {
				Class.forName(driverName);
				dbCon = DriverManager.getConnection(url + dbName, userName, password);
			}

		} catch (ClassNotFoundException cnfEx) {
			cnfEx.printStackTrace();
			return null;
		} catch (SQLException sqlEx) {
			sqlEx.printStackTrace();
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return dbCon;
	}

	public static void createTableIfNotExist(String tableName, String fromTable) throws SQLException {
		if (!tables.contains(tableName)) {
			Connection c = Database.getConnection();
			String q = "create table if not exists " + tableName + " as (select * from " + fromTable + ");";
			PreparedStatement ps = c.prepareStatement(q);
			ps.executeUpdate();
			tables.add(tableName);
			System.out.println(tableName + ": created.");
		}
	}
}